<html>

<head>
	<!--<meta http-equiv="Content-Type" content="text/html; charset=gb2312">-->
	<meta http-equiv="X-UA-Compatible" content="IE=10" />
	<title>摄像头测试</title>
	<style>
		* {
			margin: 0;
			padding: 0;
		}

		.box {
			width: 600px;
			height: 400px;
			overflow: hidden;
		}

		video {
			width: 100%;
			height: 100%;
		}

		canvas {
			position: absolute;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: -1;
		}
	</style>
	<script type="text/javascript">
		let MediaStreamTrack;
		function getMedia() {
			let constraints = {
				video: {
					width: 600,
					height: 400
				}
			};
			//获得video摄像头区域
			let video = document.getElementById("video");
			console.log(navigator.mediaDevices)
			promise = navigator.mediaDevices.getUserMedia(constraints);

			// 成功调用
			promise.then(function (MediaStream) {
				/* 使用这个MediaStream */
				video.srcObject = MediaStream;
				video.play();
				MediaStreamTrack = typeof MediaStream.stop === 'function' ? MediaStream : MediaStream.getTracks();
				console.log(MediaStream); // 对象
			})

			// 失败调用
			promise.catch(function (err) {
				/* 处理error */
				console.log(err); // 拒签
			});
		}
		function takePhoto() {
			//获得Canvas对象
			let video = document.getElementById("video");
			let canvas = document.getElementById("canvas");
			let ctx = canvas.getContext('2d');
			ctx.drawImage(video, 0, 0, 600, 400);
			let src = canvas.toDataURL("image/png");
			return src
		}
		function stopMedia() {
			MediaStreamTrack && MediaStreamTrack.forEach(t => {
				t.stop()
			});
		}
		window.onload = function () {
			getMedia()
		}
		window.onbeforeunload = function () {
			stopMedia()
		}
		window.proof = function () {
			return takePhoto()
		}
	</script>
</head>

<body>
	<div class="box">
		<video id="video" width="600" height="400" autoplay="autoplay" muted></video>
		<canvas id="canvas" width="600" height="400"></canvas>
	</div>
</body>

</html>